package com.wuhenzhizao.sku.widget;

import com.wuhenzhizao.sku.utils.AttrUtil;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 属性流布局
 *
 * @author wuhenzhizao
 * @since 2017-08-02
 */
public class FlowLayout extends ComponentContainer implements
        Component.EstimateSizeListener, ComponentContainer.ArrangeListener {
    private static final String LOG_TAG = FlowLayout.class.getSimpleName();
    private static final float NUM = 0.5f;

    /**
     * Special value for the child view spacing.
     * SPACING_AUTO means that the actual spacing is calculated according to the size of the
     * container and the number of the child views, so that the child views are placed evenly in
     * the container.
     */
    public static final int SPACING_AUTO = -65536;

    /**
     * Special value for the horizontal spacing of the child views in the last row
     * SPACING_ALIGN means that the horizontal spacing of the child views in the last row keeps
     * the same with the spacing used in the row above. If there is only one row, this value is
     * ignored and the spacing will be calculated according to childSpacing.
     */
    public static final int SPACING_ALIGN = -65537;

    private static final int SPACING_UNDEFINED = -65538;

    private static final boolean DEFAULT_FLOW = true;
    private static final int DEFAULT_CHILD_SPACING = 0;
    private static final int DEFAULT_CHILD_SPACING_FOR_LAST_ROW = SPACING_UNDEFINED;
    private static final float DEFAULT_ROW_SPACING = 0;
    private static final boolean DEFAULT_RTL = false;
    private static final int DEFAULT_MAX_ROWS = Integer.MAX_VALUE;

    private HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0x001, "TAG-" + LOG_TAG);

    private boolean mFlow = DEFAULT_FLOW;
    private int mChildSpacing = DEFAULT_CHILD_SPACING;
    private int mChildSpacingForLastRow = DEFAULT_CHILD_SPACING_FOR_LAST_ROW;
    private float mRowSpacing = DEFAULT_ROW_SPACING;
    private float mAdjustedRowSpacing = DEFAULT_ROW_SPACING;
    private boolean mRtl = DEFAULT_RTL;
    private int mMaxRows = DEFAULT_MAX_ROWS;

    /**
     * 行水平间距
     */
    private List<Float> mHorizontalSpacingForRow = new ArrayList<>();
    /**
     * 行高
     */
    private List<Integer> mHeightForRow = new ArrayList<>();
    /**
     * 行内子控件数
     */
    private List<Integer> mChildNumForRow = new ArrayList<>();

    private List<Integer> mWidthForRow = new ArrayList<>();

    /**
     * 构造
     *
     * @param context
     */
    public FlowLayout(Context context) {
        this(context, null);
    }

    /**
     * 构造
     *
     * @param context
     * @param attrs
     */
    public FlowLayout(Context context, AttrSet attrs) {
        super(context, attrs);
//        setOrientation(HORIZONTAL);
//        setChildSpacing(20);
//        setAlignment(DirectionalLayout.VERTICAL);
//        setHorizontalPosition(10,10);
        setVerticalPosition(10,10);
//        setHorizontalPadding(10,10);

        LayoutConfig layoutConfig = new LayoutConfig(
                LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_CONTENT);
        setLayoutConfig(layoutConfig);

        try {
            mFlow = AttrUtil.getBooleanValue(attrs, "flow", DEFAULT_FLOW);
            try {
                mChildSpacing = AttrUtil.getDimension(attrs, "childSpacing", DEFAULT_CHILD_SPACING);
            } catch (NumberFormatException e) {
                mChildSpacing = AttrUtil.getDimension(attrs, "childSpacing", (int) dpToPx(DEFAULT_CHILD_SPACING));
            }
            try {
                mChildSpacingForLastRow = AttrUtil.getIntegerValue(attrs, "childSpacingForLastRow", SPACING_UNDEFINED);
            } catch (NumberFormatException e) {
                mChildSpacingForLastRow = AttrUtil.getDimension(attrs, "childSpacingForLastRow", (int) dpToPx(DEFAULT_CHILD_SPACING));
            }
            try {
                mRowSpacing = AttrUtil.getIntegerValue(attrs, "rowSpacing", 0);
            } catch (NumberFormatException e) {
                mRowSpacing = AttrUtil.getDimension(attrs, "rowSpacing", (int) dpToPx(DEFAULT_ROW_SPACING));
            }
            mMaxRows = AttrUtil.getIntegerValue(attrs, "maxRows", DEFAULT_MAX_ROWS);
            mRtl = AttrUtil.getBooleanValue(attrs, "rtl", DEFAULT_RTL);
        } catch (Exception e) {
            e.printStackTrace();
        }

        setArrangeListener(this);
        setEstimateSizeListener(this);
    }

    /**
     * 测量
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     * @return boolean
     */
    @Override
    public boolean onEstimateSize(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = EstimateSpec.getSize(widthMeasureSpec);
        int widthMode = EstimateSpec.getMode(widthMeasureSpec);
        int heightSize = EstimateSpec.getSize(heightMeasureSpec);
        int heightMode = EstimateSpec.getMode(heightMeasureSpec);

        mHorizontalSpacingForRow.clear();
        mChildNumForRow.clear();
        mHeightForRow.clear();
        mWidthForRow.clear();

        int measuredHeight = 0, measuredWidth = 0, childCount = getChildCount();
        int rowWidth = 0, maxChildHeightInRow = 0, childNumInRow = 0;
        int rowSize = widthSize - getPaddingLeft() - getPaddingRight();
        boolean allowFlow = widthMode != EstimateSpec.UNCONSTRAINT && mFlow;
        int childSpacing = mChildSpacing == SPACING_AUTO && widthMode == EstimateSpec.UNCONSTRAINT
                ? 0 : mChildSpacing;
        float tmpSpacing = childSpacing == SPACING_AUTO ? 0 : childSpacing;

        for (int i = 0; i < childCount; i++) {
            Component child = getComponentAt(i);
            if (child.getVisibility() == HIDE) {
                continue;
            }

            LayoutConfig childParams = (LayoutConfig) child.getLayoutConfig();
            int horizontalMargin = 0, verticalMargin = 0;

//            if (childParams instanceof MarginLayoutParams) {
//                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, measuredHeight);
//                MarginLayoutParams marginParams = (MarginLayoutParams) childParams;
//                horizontalMargin = marginParams.leftMargin + marginParams.rightMargin;
//                verticalMargin = marginParams.topMargin + marginParams.bottomMargin;
//            } else {
//                measureChild(child, widthMeasureSpec, heightMeasureSpec);
//            }
            horizontalMargin = 10;
            verticalMargin = 10;

            int childWidth = child.getWidth() + horizontalMargin;
            int childHeight = child.getHeight() + verticalMargin;

            // 换行操作
            if (allowFlow && rowWidth + childWidth > rowSize) { // Need flow to next row
                // Save parameters for current row 保存当前行参数
                mHorizontalSpacingForRow.add(
                        getSpacingForRow(childSpacing, rowSize, rowWidth, childNumInRow));
                mChildNumForRow.add(childNumInRow);
                mHeightForRow.add(maxChildHeightInRow);
                mWidthForRow.add(rowWidth - (int) tmpSpacing);
                if (mHorizontalSpacingForRow.size() <= mMaxRows) {
                    measuredHeight += maxChildHeightInRow;
                }
                measuredWidth = Math.max(measuredWidth, rowWidth);

                // Place the child view to next row 将子控件放入下一行
                childNumInRow = 1;
                rowWidth = childWidth + (int) tmpSpacing;
                maxChildHeightInRow = childHeight;
            } else { // 在当前行添加子控件
                childNumInRow++;
                rowWidth += childWidth + tmpSpacing;
                maxChildHeightInRow = Math.max(maxChildHeightInRow, childHeight);
            }
        }

//        HiLog.error(logLabel, "1111111--allowFlow-" + allowFlow + "-rowSize-" + rowSize + "-rowWidth-"
//                + rowWidth + "-rowSize-" + rowSize + "-measuredHeight-" + measuredHeight
//                + "-measuredWidth-" + measuredWidth + "-maxChildHeightInRow-" + maxChildHeightInRow
//                + "-childNumInRow-" + childNumInRow + "-childSpacing-" + childSpacing );

        // Measure remaining child views in the last row
        if (mChildSpacingForLastRow == SPACING_ALIGN) {
            // For SPACING_ALIGN, use the same spacing from the row above if there is more than one
            // row.
            if (mHorizontalSpacingForRow.size() >= 1) {
                mHorizontalSpacingForRow.add(
                        mHorizontalSpacingForRow.get(mHorizontalSpacingForRow.size() - 1));
            } else {
                mHorizontalSpacingForRow.add(
                        getSpacingForRow(childSpacing, rowSize, rowWidth, childNumInRow));
            }
        } else if (mChildSpacingForLastRow != SPACING_UNDEFINED) {
            // For SPACING_AUTO and specific DP values, apply them to the spacing strategy.
            mHorizontalSpacingForRow.add(
                    getSpacingForRow(mChildSpacingForLastRow, rowSize, rowWidth, childNumInRow));
        } else {
            // For SPACING_UNDEFINED, apply childSpacing to the spacing strategy for the last row.
            mHorizontalSpacingForRow.add(
                    getSpacingForRow(childSpacing, rowSize, rowWidth, childNumInRow));
        }

        mChildNumForRow.add(childNumInRow);
        mHeightForRow.add(maxChildHeightInRow);
        mWidthForRow.add(rowWidth - (int) tmpSpacing);
        if (mHorizontalSpacingForRow.size() <= mMaxRows) {
            measuredHeight += maxChildHeightInRow;
        }
        measuredWidth = Math.max(measuredWidth, rowWidth);

        if (childSpacing == SPACING_AUTO) {
            measuredWidth = widthSize;
        } else if (widthMode == EstimateSpec.UNCONSTRAINT) {
            measuredWidth = measuredWidth + getPaddingLeft() + getPaddingRight();
        } else {
            measuredWidth = Math.min(measuredWidth + getPaddingLeft() + getPaddingRight(), widthSize);
        }

        measuredHeight += getPaddingTop() + getPaddingBottom();
        int rowNum = Math.min(mHorizontalSpacingForRow.size(), mMaxRows);
        float rowSpacing = mRowSpacing == SPACING_AUTO && heightMode == EstimateSpec.UNCONSTRAINT
                ? 0 : mRowSpacing;
        if (rowSpacing == SPACING_AUTO) {
            if (rowNum > 1) {
                mAdjustedRowSpacing = (float) (heightSize - measuredHeight) / (rowNum - 1);
            } else {
                mAdjustedRowSpacing = 0;
            }
            measuredHeight = heightSize;
        } else {
            mAdjustedRowSpacing = rowSpacing;
            if (rowNum > 1) {
                measuredHeight = heightMode == EstimateSpec.UNCONSTRAINT
                        ? ((int) (measuredHeight + mAdjustedRowSpacing * (rowNum - 1)))
                        : (Math.min((int) (measuredHeight + mAdjustedRowSpacing * (rowNum - 1)),
                        heightSize));
            }
        }

        measuredWidth = widthMode == EstimateSpec.PRECISE ? widthSize : measuredWidth;
        measuredHeight = heightMode == EstimateSpec.PRECISE ? heightSize : measuredHeight;
        setEstimatedSize(measuredWidth, measuredHeight);

        return false;
    }

    /**
     * 布局
     *
     * @param left
     * @param top
     * @param right
     * @param bottom
     * @return boolean
     */
    @Override
    public boolean onArrange(int left, int top, int right, int bottom) {
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int x = mRtl ? (getWidth() - paddingRight) : paddingLeft;
        int y = paddingTop;

        int rowCount = mChildNumForRow.size(), childIdx = 0;
        HiLog.error(logLabel,"TAG-rowCount-"+rowCount);

        int horizontalGravity = -1 & LayoutAlignment.LEFT;

        int horizontalPadding = paddingLeft + paddingRight, layoutWidth = right - left;
        x += getHorizontalGravityOffsetForRow(horizontalGravity, layoutWidth, horizontalPadding, 0);
        for (int row = 0; row < rowCount; row++) {
            int childNum = mChildNumForRow.get(row);
            int rowHeight = mHeightForRow.get(row);
            float spacing = mHorizontalSpacingForRow.get(row);
            for (int i = 0; i < childNum && childIdx < getChildCount(); ) {
                Component child = getComponentAt(childIdx++);
                if (child.getVisibility() == HIDE) {
                    continue;
                } else {
                    i++;
                }

                LayoutConfig childParams = (LayoutConfig) child.getLayoutConfig();
                int marginLeft = 0, marginTop = 0, marginRight = 0,marginBottom;
//                if (childParams instanceof MarginLayoutParams) {
//                    MarginLayoutParams marginParams = (MarginLayoutParams) childParams;
//                    marginLeft = marginParams.leftMargin;
//                    marginRight = marginParams.rightMargin;
//                    marginTop = marginParams.topMargin;
//                }

                marginLeft = 10;
                marginRight = 10;
                marginTop = 10;
                marginBottom = 10;


                int childWidth = child.getWidth();
                int childHeight = child.getHeight();
                if (mRtl) {
                    ComponentContainer.LayoutConfig layoutConfig = new ComponentContainer.LayoutConfig();
                    layoutConfig.setMargins(marginLeft, marginTop,
                            marginRight, marginBottom);
                    child.setLayoutConfig(layoutConfig);
                    x -= childWidth + spacing + marginLeft + marginRight;
                } else {
                    ComponentContainer.LayoutConfig layoutConfig = new ComponentContainer.LayoutConfig();
                    layoutConfig.setMargins(marginLeft, marginTop,
                            marginRight, marginBottom);
                    child.setLayoutConfig(layoutConfig);
                    x += childWidth + spacing + marginLeft + marginRight;
                }
            }
            x = mRtl ? (getWidth() - paddingRight) : paddingLeft;
            x += getHorizontalGravityOffsetForRow(
                    horizontalGravity, layoutWidth, horizontalPadding, row + 1);
            y += rowHeight + mAdjustedRowSpacing;
        }
        return false;
    }

    /**
     * 获取水平方向偏移
     *
     * @param horizontalGravity
     * @param parentWidth
     * @param horizontalPadding
     * @param row
     * @return 偏移量
     */
    private int getHorizontalGravityOffsetForRow(int horizontalGravity, int parentWidth, int horizontalPadding, int row) {
        if (mChildSpacing == SPACING_AUTO || row >= mWidthForRow.size()
                || row >= mChildNumForRow.size() || mChildNumForRow.get(row) <= 0) {
            return 0;
        }

        int offset = 0;
        switch (horizontalGravity) {
            case LayoutAlignment.HORIZONTAL_CENTER:
                offset = (parentWidth - horizontalPadding - mWidthForRow.get(row)) / 2;
                break;
            case LayoutAlignment.RIGHT:
                offset = parentWidth - horizontalPadding - mWidthForRow.get(row);
                break;
            default:
                break;
        }
        return offset;
    }

    /**
     * Returns whether to allow child views flow to next row when there is no enough space.
     *
     * @return Whether to flow child views to next row when there is no enough space.
     */
    public boolean isFlow() {
        return mFlow;
    }

    /**
     * Sets whether to allow child views flow to next row when there is no enough space.
     *
     * @param flow true to allow flow. false to restrict all child views in one row.
     */
    public void setFlow(boolean flow) {
        mFlow = flow;
        postLayout();
    }

    /**
     * Returns the horizontal spacing between child views.
     *
     * @return The spacing, either {@link FlowLayout1#SPACING_AUTO}, or an fixed size in pixels.
     */
    public int getChildSpacing() {
        return mChildSpacing;
    }

    /**
     * Sets the horizontal spacing between child views.
     *
     * @param childSpacing The spacing, either {@link FlowLayout1#SPACING_AUTO}, or an fixed size in
     *                     pixels.
     */
    public void setChildSpacing(int childSpacing) {
        mChildSpacing = childSpacing;
        postLayout();
    }

    /**
     * Returns the horizontal spacing between child views of the last row.
     *
     * @return The spacing, either {@link FlowLayout1#SPACING_AUTO},
     * {@link FlowLayout1#SPACING_ALIGN}, or an fixed size in pixels
     */
    public int getChildSpacingForLastRow() {
        return mChildSpacingForLastRow;
    }

    /**
     * Sets the horizontal spacing between child views of the last row.
     *
     * @param childSpacingForLastRow The spacing, either {@link FlowLayout1#SPACING_AUTO},
     *                               {@link FlowLayout1#SPACING_ALIGN}, or an fixed size in pixels
     */
    public void setChildSpacingForLastRow(int childSpacingForLastRow) {
        mChildSpacingForLastRow = childSpacingForLastRow;
        postLayout();
    }

    /**
     * Returns the vertical spacing between rows.
     *
     * @return The spacing, either {@link FlowLayout1#SPACING_AUTO}, or an fixed size in pixels.
     */
    public float getRowSpacing() {
        return mRowSpacing;
    }

    /**
     * Sets the vertical spacing between rows in pixels. Use SPACING_AUTO to evenly place all rows
     * in vertical.
     *
     * @param rowSpacing The spacing, either {@link FlowLayout1#SPACING_AUTO}, or an fixed size in
     *                   pixels.
     */
    public void setRowSpacing(float rowSpacing) {
        mRowSpacing = rowSpacing;
        postLayout();
    }

    /**
     * Returns the maximum number of rows of the FlowLayout.
     *
     * @return The maximum number of rows.
     */
    public int getMaxRows() {
        return mMaxRows;
    }

    /**
     * Sets the number of row of the FlowLayout to be at most maxRows size.
     *
     * @param maxRows The maximum number of rows.
     */
    public void setMaxRows(int maxRows) {
        mMaxRows = maxRows;
        postLayout();
    }

    /**
     * 获取行距
     *
     * @param spacingAttribute
     * @param rowSize
     * @param usedSize
     * @param childNum
     * @return float
     */
    private float getSpacingForRow(int spacingAttribute, int rowSize, int usedSize, int childNum) {
        float spacing;
        if (spacingAttribute == SPACING_AUTO) {
            if (childNum > 1) {
                spacing = (float) (rowSize - usedSize) / (childNum - 1);
            } else {
                spacing = 0;
            }
        } else {
            spacing = spacingAttribute;
        }
        return spacing;
    }

    /**
     * 转换px
     *
     * @param dpValue
     * @return float
     */
    private float dpToPx(float dpValue) {
        Optional<Display> defaultDisplay = DisplayManager.getInstance().getDefaultDisplay(this.getContext());
        DisplayAttributes attributes = defaultDisplay.get().getAttributes();
        float scale = attributes.densityPixels;
        return (float) (dpValue * scale + NUM);
    }

}